#!/bin/bash

source_path=""
rpm_name=""
rpm_branch=""
patches_path=""
path_file_name=""
tmp_path=/opt/tmp_download_rpms
# The rpm package that needs to be installed when compiling
requires_rpms=""
spec_file=""

function check_patch() {
    if [[ -z ${patches_path} ]]; then
        echo "[ERROR] Input patch is null"
        exit 1
    fi

    for patch in ${patches_path[@]}; do
        if [[ ! -f ${patch} ]]; then
            echo "[ERROR] ${patch} is not found"
            exit 1
        fi
    done
}

function check_local() {
    if [[ ! -d ${source_path} ]]; then
        echo "[ERROR] The source package path ${source_path} does not exist"
        exit 1
    fi

    check_patch
}

function check_remote() {
    if [[ -z ${rpm_name} ]] || [[ -z ${rpm_branch} ]]; then
        echo "[ERROR] Incorrect input,Please use [ /bin/bash add_patch.sh 'name of package' 'branch of package' 'path of patch file']"
        exit 1
    fi

    check_patch
}

function clear_env() {
    echo "[INFO] Create /root/rpmbuild"
    # rm -rf /root/rpmbuild/*
    if [[ ! -d /root/rpmbuild/ ]];then
        mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SPECS,SOURCES,SRPMS}
    fi
}

function pre_env() {
    if [ ! -d ${tmp_path} ]; then
        mkdir -p ${tmp_path}
        echo "[INFO] Create tmp path ${tmp_path}"
    fi
    cd ${tmp_path}
    rm -rf ${rpm_name}
}

function git_clone() {
    echo "[INFO] Start to git clone ${rpm_name}"
    git_status=$(rpm -qa git)
    if [[ -z ${git_status} ]]; then
        yum install git -y
        git_status=$(rpm -qa git)
        if [[ -z ${git_status} ]]; then
            echo "[ERROR] Git install failed"
            exit 1
        fi
    fi

    cd ${tmp_path}
    git clone -b ${rpm_branch} https://gitee.com/src-openeuler/${rpm_name}.git >/dev/null
    rpm_path=$(ls | grep ${rpm_name})
    if [[ -z ${rpm_path} ]]; then
        echo "[ERROR] git clone ${rpm_name} failed, please check path /opt/cve_patch_tmp"
        exit 1
    fi

    source_path=${tmp_path}/${rpm_name}
}

function update_spec() {
    echo "[INFO] Start to update spec file"
    cd ${source_path}
    spec_file=$(ls | grep *.spec | grep -v *.bak)
    if [[ -z ${spec_file} ]]; then
        echo "[ERROR] spec file is not found"
        exit 1
    fi
    # backup spec
    /bin/cp ${spec_file} ${spec_file}.bak
    # update Release
    release_version=$(grep "Release:" ${spec_file} | awk -F " " '{print $NF}')
    new_release=$(expr ${release_version} + 1)
    sed -i "s/Release:.*${release_version}/Release:        ${new_release}/" ${spec_file}
    # add Patch***
    last_patch=$(grep "Patch.*:" ${spec_file} | sed -n '$p')
    if [[ -z ${last_patch} ]]; then
        source_row=$(grep -n "Source.*:" ${spec_file} | sed -n '$p' | awk -F ':' '{print $1}')
        sed -ie "${source_row}G;${source_row}a Patch0000:      ${path_file_name}" ${spec_file}
    else
        last_patch_row=$(grep -n "${last_patch}" ${spec_file} | awk -F ':' '{print $1}')
        last_patch_num=$(echo ${last_patch} | awk -F ':' '{print $1}' | awk -F 'Patch' '{print $2}')
        patch_name_len=${#last_patch_num}
        new_patch_num=$(expr ${last_patch_num} + 1)
        new_patch_num=$(printf "%0${patch_name_len}d" ${new_patch_num})
        sed -i "${last_patch_row}a Patch${new_patch_num}:      ${path_file_name}" ${spec_file}
    fi
    # add changelog
    change_log_row=$(grep -n '%changelog' ${spec_file} | sed -n '$p' | awk -F ':' '{print $1}')
    date_now=$(date '+%a %b %d %Y')
    version=$(grep 'Version:' ${spec_file} | awk -F ' ' '{print $NF}')
    log_description="- add ${path_file_name}"
    log_title="* ${date_now} robot <robot@robot.com> - ${version}-${new_release}"
    sed -i "${change_log_row}G" ${spec_file}
    sed -i "${change_log_row}a ${log_description}" ${spec_file}
    sed -i "${change_log_row}a ${log_title}" ${spec_file}

    echo "[INFO] Update spec file success"
}

function mv_source_file() {
    echo "[INFO] Copy source file to /root/rpmbuild"
    cd ${source_path}
    spec_file=$(ls | grep *.spec | grep -v *.bak)
    /bin/cp ${patches_path} ${source_path}
    /bin/cp * /root/rpmbuild/SOURCES
    /bin/cp *.spec /root/rpmbuild/SPECS
}

function rpm_build() {
    echo "[INFO] Start to rpmbuild"
    rpmbuild_status=$(rpm -qa rpm-build)
    if [[ -z ${rpmbuild_status} ]]; then
        yum install rpm-build -y >/dev/null 2>&1
        rpmbuild_status=$(rpm -qa rpm-build)
        if [[ -z ${rpmbuild_status} ]]; then
            echo "[ERROR] Install rpm-build failed"
            exit 1
        fi
    fi
    rpmbuild -bb /root/rpmbuild/SPECS/${spec_file} >./rpmbuild.log 2>&1
    if [[ $? -eq 0 ]]; then
        echo "[INFO] build success"
        exit 0
    elif [[ -n $(grep "Failed build dependencies" ./rpmbuild.log) ]]; then
        requires_rpms=$(grep -r "is needed by" ./rpmbuild.log | awk -F " " '{print $1}')
        echo ${requires_rpms} >./requires_rpms.log
        for rpm in ${requires_rpms[@]}; do
            yum install ${rpm} -y >/dev/null 2>&1
            if [[ $? -eq 0 ]]; then
                echo "[INFO] Successfully install dependent package ${rpm}"
            else
                echo "[ERROR] Failed to install dependent package ${rpm}"
                exit 1
            fi
        done
        rpm_build
    else
        echo "[ERROR] build failed,log is ${source_path}/rpmbuild.log"
        exit 1
    fi
}

function main() {
    input_params_length=$#
    if [[ ${input_params_length} -eq 2 ]]; then
        source_path=$1
        patches_path=$2
        check_local
        clear_env
        for patch in ${patches_path[@]};do
            path_file_name=$(echo ${patch} | awk -F "/" '{print $NF}' | awk -F "\\" '{print $NF}')
            update_spec
        done
    elif [[ ${input_params_length} -eq 3 ]]; then
        rpm_name=$1
        rpm_branch=$2
        patches_path=$3
        check_remote
        clear_env
        pre_env
        git_clone
        for patch in ${patches_path[@]};do
            path_file_name=$(echo ${patch} | awk -F "/" '{print $NF}' | awk -F "\\" '{print $NF}')
            update_spec
        done
    else
        echo "[ERROR] Incorrect input,please use: 
        1、 /bin/bash add_patch.sh 'Source package path' 'Patch file path' 
        2、 /bin/bash add_patch.sh 'name of package' 'branch of package' 'path of patch file'"
        exit 1
    fi

    mv_source_file
    rpm_build
}

main "$@"
exit $?
